import storage from './storage';
const debugMode = true; // 调试模式下本地网络访问

// Release
export const cloudInfo = {
    env: 'prod-5gffsrjke05f512a',
    service: 'django-rwxr',
    cloudPrefix: 'cloud://prod-5gffsrjke05f512a.7072-prod-5gffsrjke05f512a-1317739850/'
}

// TODO: Remove when release
// Debug
// export const cloudInfo = {
//     env: 'prod-5gffsrjke05f512a',
//     service: 'health_management_backend',
//     cloudPrefix: 'cloud://prod-5gffsrjke05f512a.7072-prod-5gffsrjke05f512a-1317739850/'
// }

const getPrivilege = async () => {
    const userInfo = await getUserInfo();
    if (userInfo === null) {
        console.error('get privilege failed: user info is null');
        return 0;
    }
    return userInfo.privilege;
}

const init = async () => {
    wx.cloud.init()
}

export const request = async (params) => {
    // request parameters
    console.log("[request]: ", params, "send request");
    const url = params.url;
    const { data } = params;
    const method = params?.method ?? 'GET';
    const headers = { 'Content-Type': 'application/json', ...params.headers };
    // callback
    try {
        const res = await wx.cloud.callContainer({
            config: {
                env: cloudInfo.env, // 微信云托管的环境ID
            },
            path: url,
            method: method, // 按照自己的业务开发，选择对应的方法
            header: {
                'X-WX-SERVICE': cloudInfo.service,
                ...headers,
            },
            data: data,
        });
        console.log("[request]: ", params, "request success:", res);
        params.success && params.success(res);
        return res;
    } catch (error) {
        console.error("request failed: ", error);
        params.fail && params.fail(error);
        return Promise.reject(error);
    }
}

const uploadFile = async (params) => {
    const { filePath, name, success, fail } = params;
    console.log("uploadFile: ", { filePath, name });
    // TODO: 后端添加对象存储适配
    const res = await wx.cloud.uploadFile({
        cloudPath: name, // 对象存储路径，使用name作为文件名
        filePath, // 微信本地文件路径
        config: {
            env: cloudInfo.env // 微信云托管环境ID
        },
        success: (res) => {
            console.log("upload file success: ", res);
            success && success(res);
        },
        fail: (error) => {
            console.error("upload file failed: ", error);
            fail && fail(error);
        }
    });
    return res;
}

// 获取用户信息
// 格式 {id, username, avatarUrl, }
const userInfoStatus = {
    isDirty: true,
};

export const setUserInfoStatus = ({isDirty = true} = {}) => {
    userInfoStatus.isDirty = isDirty;
}

export const getUserInfo = async ({ showLoading = false, useCache = true } = {}) => {
    let userInfo = null;
    if (useCache && !userInfoStatus.isDirty) {
        userInfo = storage.get('user_info');
        if (userInfo) {
            return userInfo;
        }
    }
    console.log('geting user info from backend');
    if (showLoading)
    {
        uni.showLoading({
            title: "加载中",
        })
    }
    try {
        const res = await request({
            url: '/user/get/id/',
        })
        userInfo = res.data.user;
        storage.set('user_info', userInfo);
        userInfoStatus.isDirty = false;
        console.log("Get userInfo from server: ", userInfo);
    } catch (error) {
        console.error('get user info failed:', error);
        return Promise.reject(error);
    }
    if (showLoading)
        uni.hideLoading();
    return userInfo;
}

// 获取用户位置信息
const getUserLocation = async ({ success = undefined, fail = undefined, showLoading = false } = {}) => {
    let userLocation = null;
    if (showLoading)
    {
        uni.showLoading({
            title: "加载中",
        })
    }
    const res = await request({
        url: '/user/address/',
        success: (res) => {
            console.log("get location response:", res);
            if (res.statusCode !== 200 || res.data.city == null || res.data.city.length === 0) {
                storage.setPermanent('user_location', null);
                console.error("get location failed:", res);
                fail && fail(res);
                return;
            }
            userLocation = res.data;
            storage.setPermanent('user_location', userLocation);
            success && success(userLocation);
        },
        fail: (error) => {
            storage.setPermanent('user_location', null);
            console.error("get location failed:", error);
            fail && fail(error);
        }
    });
    if (showLoading)
        uni.hideLoading();
    return userLocation;
}

const getFileUrl = async (fileID) => {
    const res = await wx.cloud.getTempFileURL({
        fileList: [{
            fileID: fileID,
        }],
    });
    if (res.fileList.length === 0 || res.fileList[0].tempFileURL === null) {
        console.error("get file url failed: ", res);
        return null;
    }
    return res.fileList[0].tempFileURL;
};

const getImageUrl = (path) => {
    return cloudInfo.cloudPrefix + "statics/image/" + path.replace(/^\/?/, "");
}

const getCloudPath = (path) => {
    return path.startsWith("cloud://") ? path : cloudInfo.cloudPrefix + path.replace(/^\/?/, "");
}

/**
 * Generate unique filename for file upload
 * @returns {string} - Unique filename without path and extension
 */
export const generateUniqueFileName = () => {
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substring(2, 8);
    return `${timestamp}_${randomStr}`;
}

export const requests = {
    request,
    uploadFile,
    init,
    // login,
    getPrivilege,
    setUserInfoStatus,
    getUserInfo,
    getUserLocation,
    getCloudPath,
    getImageUrl,
    generateUniqueFileName,
};

export default requests;